package shop_cart

import (
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/api"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/forms"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/global"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/proto"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
)

func List(ctx *gin.Context) {
	userIdStr, _ := ctx.Get("id")
	userId := userIdStr.(int64)
	fmt.Println(userId)
	resp, err := global.OrderSrvClient.CartItemList(ctx, &proto.UserInfo{
		Id: userId,
	})
	if err != nil {
		zap.S().Errorw("[List] 查询 [购物车列表] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ids := make([]int64, 0)
	for _, item := range resp.Data {
		ids = append(ids, item.GoodsId)
	}
	if len(ids) == 0 {
		ctx.JSON(200, gin.H{
			"total": 0,
		})
		return
	}
	// 调用商品服务
	goodsResp, err := global.GoodsSrvClient.BatchGetGoods(ctx, &proto.BatchGoodsIdInfo{
		Id: ids,
	})
	if err != nil {
		zap.S().Errorw("[List] 批量查询 [商品列表] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	reMap := gin.H{
		"total": resp.Total,
	}
	goodsList := make([]interface{}, 0)
	for _, item := range resp.Data {
		for _, good := range goodsResp.Data {
			if item.GoodsId == good.Id {
				tmpMap := map[string]interface{}{}
				tmpMap["id"] = item.Id
				tmpMap["goods_id"] = item.GoodsId
				tmpMap["goods_name"] = good.Name
				tmpMap["goods_price"] = good.ShopPrice
				tmpMap["goods_image"] = good.GoodsFrontImage
				tmpMap["nums"] = item.Nums
				tmpMap["checked"] = item.Checked

				goodsList = append(goodsList, tmpMap)
			}
		}
	}
	reMap["data"] = goodsList
	ctx.JSON(200, reMap)
}

func New(ctx *gin.Context) {
	itemForm := forms.ShopCartItemForm{}
	if err := ctx.ShouldBindJSON(&itemForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	_, err := global.GoodsSrvClient.GetGoodsDetail(ctx, &proto.GoodInfoRequest{
		Id: itemForm.GoodsId,
	})
	if err != nil {
		zap.S().Errorw("[New] 查询 [商品信息] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	// 添加商品到购物车之前，需要判断商品是否存在
	invResp, err := global.InventorySrvClient.InvDetail(ctx, &proto.GoodsInvInfo{
		GoodsId: itemForm.GoodsId,
	})
	if err != nil {
		zap.S().Errorw("[New] 查询 [库存信息] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	// 添加商品到购物车的数量不能超过库存数量
	if itemForm.Nums > invResp.Num {
		ctx.JSON(200, gin.H{
			"nums": "库存不足",
		})
		return
	}
	uIdStr, _ := ctx.Get("id")
	uId := uIdStr.(int64)
	resp, err := global.OrderSrvClient.CreateCartItem(ctx, &proto.CartItemRequest{
		UserId:  uId,
		GoodsId: itemForm.GoodsId,
		Nums:    itemForm.Nums,
		Checked: false,
	})
	if err != nil {
		zap.S().Errorw("[New] 添加 [购物车] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(200, gin.H{
		"id": resp.Id,
	})
}

func Update(ctx *gin.Context) {
	itemForm := forms.ShopCartItemUpdateForm{}
	if err := ctx.ShouldBindJSON(&itemForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	idStr, _ := ctx.Get("id")
	uid, _ := idStr.(int64)
	goodsIdStr := ctx.Param("id")
	goodsId, _ := strconv.ParseInt(goodsIdStr, 10, 64)
	_, err := global.OrderSrvClient.UpdateCartItem(ctx, &proto.CartItemRequest{
		UserId:  uid,
		GoodsId: goodsId,
		Nums:    itemForm.Nums,
		Checked: *itemForm.Checked,
	})
	if err != nil {
		zap.S().Errorw("[Update] 更新 [购物车] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(200, gin.H{
		"status": "更新成功",
	})
}

func Delete(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ctx.JSON(400, gin.H{
			"msg": "url格式出错",
		})
		return
	}
	uidStr, _ := ctx.Get("id")
	uid := uidStr.(int64)
	_, err = global.OrderSrvClient.DeleteCartItem(ctx, &proto.CartItemRequest{
		UserId:  uid,
		GoodsId: id,
	})
	if err != nil {
		zap.S().Errorw("[Delete] 删除 [购物车] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(200, gin.H{
		"status": "删除成功",
	})
}
